package Q203

class Main {
}

class ListNode {
    var `val` = 0
    var next: ListNode? = null

    constructor() {}
    constructor(`val`: Int) {
        this.`val` = `val`
    }

    constructor(`val`: Int, next: ListNode?) {
        this.`val` = `val`
        this.next = next
    }
}

class Solution {
    /**
     * 解法1
     * @param head
     * @param val
     * @return
     */
    fun removeElements(head: ListNode?, `val`: Int): ListNode? {
        var head = head
        while (head != null && head.`val` == `val`) {
            head = head.next
        }
        if (head == null) {
            return null
        }
        var pre: ListNode = head
        var res = head.next
        while (res != null) {
            if (res.`val` == `val`) {
                pre.next = res.next
            } else {
                pre = res
            }
            res = res.next
        }
        return head
    }
}